<template>
    <div class="observerLibrary-increase">
        <!-- 新增弹窗 -->
        <a-modal
        class="drug-production-template-model"
         :visible="visibleShow" 
         :title="formState.id?'编辑':'新增'" 
         @ok="handleOk" 
         :confirmLoading="confirmLoading"
         @cancel="visibleShow = false"
         width="80%"
         :dialogStyle="{top:'5px'}"
         :forceRender="true"
         
         >
            <template slot="footer">
                <div style="display: flex;justify-content: flex-end;">
                    <a-form layout="inline" style="display: flex;justify-content: flex-end;">
                        <a-form-item>
                            <a-button class="blue-btn" type="primary" @click="visibleShow = false" icon>关闭</a-button>
                        </a-form-item>
                        <a-form-item>
                            <a-button class="blue-btn" type="primary" @click="handleOk(true)" icon>保存</a-button>
                        </a-form-item>
                        <a-form-item>
                            <a-button class="red-btn" type="primary" @click="handleOk(true)" >保存并关闭</a-button>
                        </a-form-item>
                    </a-form>
                </div>
            </template>
            <a-spin size="large" :spinning="spinning">
                <a-form-model
                    ref="ruleForm"
                    :model="formState"
                    :rules="rules"
                    layout="inline"
                    class="drug-production-template-form"
                    :key="drugProductionTemplateKey"
                >
                    <a-form-model-item ref="fmbbt" label="模板标题" prop="fmbbt" >
                        <a-input
                        placeholder="请输入模板标题"
                        v-model:value="formState.fmbbt"/>
                    </a-form-model-item>
                    <a-form-model-item ref="fmblx1" label="模板类型1" prop="fmblx1">
                        <a-input
                            v-if="!formState.id"
                            placeholder="请输入模板类型1"
                            v-model:value="formState.fmblx1"
                        />
                        <span v-else>{{ formState.fmblx1 }}</span>
                    </a-form-model-item>
                    <a-form-model-item ref="fmblx2" label="模板类型2">
                        <a-input
                        placeholder="请输入模板类型2"
                        v-model:value="formState.fmblx2"/>
                    </a-form-model-item>
                    <a-form-model-item ref="fmblx3" label="模板类型3">
                        <a-input
                        placeholder="请输入模板类型3"
                        v-model:value="formState.fmblx3"/>
                    </a-form-model-item>
                    <a-form-model-item ref="fmblx4" label="模板类型4">
                        <a-input
                        placeholder="请输入模板类型4"
                        v-model:value="formState.fmblx4"/>
                    </a-form-model-item>
                    <a-form-model-item ref="fmbzt" label="模板状态">
                        <compSelector
                        style="margin-top: 3px;"
                        widthPercentile="100%"
                        v-model="formState.fmbzt"
                        :compType="typeSelect"
                        defaultValue="有效"
                        dictionaryType="文件模板状态"
                        />
                    </a-form-model-item>
                    <a-form-model-item label="上传模板" >
                        <div v-if="!formState.id">
                            <a-button class="blue-btn" type="default"  icon="import" @click="$message.warning('请先保存数据')">上传</a-button>
                        </div>
                        <div v-else>
                            <a-upload :beforeUpload="beforeUpload" :showUploadList="false"  action="" @change="leadingInClick" :file-list="fileList">
                                <a-button class="blue-btn" type="default"  icon="import">上传</a-button>
                            </a-upload>
                            <div v-if="fileList.length" :key="fileListNameKey" style="color: #1890ff;cursor:pointer;" @click="DownloadTemplateClick(formState)">
                                {{ fileList[0].name }}
                                <!-- <a-icon class="delete-icon-v" type="delete" @click="handleRemove" /> -->
                            </div>
                        </div>
                    </a-form-model-item>
                    <a-form-model-item label="编辑模板" v-if="renovate && fileList.length">
                        <a-button v-if="editMode == '客户端模式'" class="blue-btn" type="primary" @click="onlineEditingClick(formState)">在线编辑</a-button>
                        <a-button v-if="editMode == '服务端模式'" class="blue-btn" type="primary" @click="serverEdit(formState)" >编辑</a-button>
                    </a-form-model-item>
                </a-form-model>
                <div class="process-handling-card" >
                    <a-tabs type="card" v-model:activeKey="activeKey" @change="tabPaneChange">
                        <a-tab-pane key="审评情况描述" tab="审评情况描述"></a-tab-pane>
                        <a-tab-pane key="审评项目" tab="审评项目"></a-tab-pane>
                    </a-tabs>
                </div>
                <div class="fileTemplate-increase-tabs">
                    <div v-if="activeKey == '审评情况描述'">
                        <div class="item-box-v" >
                            <span class="text-v">审评情况描述标题：</span>
                            <a-input style="flex: 1;" placeholder="请输入审评情况描述标题" v-model:value="formState.fmsmbbt"/>
                        </div>
                        <commpKindeditor
                            :id="fileTemplateIncreaseKindeditorId" 
                            :key="fileTemplateIncreaseKindeditorKey"
                            :height="windowInnerHeight - 430+'px'" 
                            width="100%" 
                            :content.sync="formState.fmsmbnr"
                            :afterChange="()=>{}"
                            :loadStyleMode="false"
                        ></commpKindeditor>
                    </div>
                    <div v-if="activeKey == '审评项目'">
                        <div class="item-box-v">
                            <span class="text-v" >审评项目标题：</span>
                            <a-input style="flex: 1;" placeholder="请输入审评项目标题" v-model:value="formState.fjcxmbt"/>
                        </div>
                        <commpVxeTable
                        :key="tableKey"
                        :isCanWrap="true"
                        :config="dataTableConfig"
                        :columns="columnsVxe"
                        :formItem="formItem"
                        :conditionBtnRow="true"
                        :tablePadding="'0'"
                        :assembleWidth="940"
                        :arrangeSearchNum="2"
                        ref="acceptanceRegistrationRef"
                    >
                        <template v-slot:externalOperations="{data}"  >
                            <vxe-form-item>
                                <template>
                                    <a-button v-if="formState.id" class="blue-btn" type="primary" @click="addition()" icon="plus">新增</a-button>
                                </template>
                            </vxe-form-item>
                        </template>
                        <template v-slot:operation_btn="{row}">
                            <a-form layout="inline" class="search-form" >
                                <a-form-item >
                                    <a-icon style="font-size:20px;color:#5ca3e5;" type="arrow-up" @click="upAndDownClick(row,true)"/>
                                </a-form-item>
                                <a-form-item >
                                    <a-icon style="font-size:20px;color:#5ca3e5;" type="arrow-down" @click="upAndDownClick(row,false)"/>
                                </a-form-item>
                                <a-form-item >
                                    <a-button class="blue-btn" type="primary" @click="handleClick(row)" icon="edit">编辑</a-button>
                                </a-form-item>
                                <a-form-item >
                                    <a-button class="red-btn" type="primary" @click="deletionClick(row)" icon="delete">删除</a-button>
                                </a-form-item>
                            </a-form>
                        </template>
                    </commpVxeTable>
                    </div>
                </div>
                <serverEditing ref="serverEditingRef" @refreshChange="manualSuccess"/>
            </a-spin>
            <a-modal
                :title="chapterTitle"
                :visible="chaptervisible"
                @ok="chapterOk"
                @cancel="chaptervisible = false"
                width="70%"
                :forceRender="true"
                class="fileTemplate-chapter-modal"
                
            >
                <a-form-model
                    ref="ruleForm1"
                    :model="chapterModel"
                    :rules="rules1"
                    :key="chapterKey"
                    layout="horizontal"
                    :label-col="{ span: 6 }"
                    :wrapper-col="{ span: 18 }"
                    class="fileTemplate-chapter-box"
                >
                    <!-- <a-form-model-item ref="forder" label="序号" prop="forder" >
                        <a-input
                        placeholder="请输入序号"
                        v-model:value="chapterModel.forder"/>
                    </a-form-model-item> -->
                    <a-form-model-item ref="fzjmc" label="审评项目名称" prop="fzjmc" >
                        <a-input
                        placeholder="请输入审评项目名称"
                        v-model:value="chapterModel.fzjmc"/>
                    </a-form-model-item>
                    <a-form-model-item ref="fmsmbnr" label="模板描述" prop="fmsmbnr" >
                        <commpKindeditor
                            :id="fchapterKindeditorId" 
                            :key="chapterKindeditorKey"
                            :height="windowInnerHeight - 375+'px'" 
                            width="100%" 
                            :content.sync="chapterModel.fmsmbnr"
                            :afterChange="()=>{}"
                            :loadStyleMode="false"
                        ></commpKindeditor>
                    </a-form-model-item>
                </a-form-model>
            </a-modal>
        </a-modal>
    </div>
</template>
<script>
import serverEditing from '@/components/comp-model-series/server-editing.vue'
import {typeInput, typeNumber, typeSelect, typeCheckbox, typeRadio} from '@/components/compSearchCriteria/ContractType'
import compSelector from '@/components/compSelector/compSelector'
import validator from '@/common/validator'
import blobType from '@/common/blobType'
import {
    addServe,
    addTemplateServe,
    deleteTemplateServe,
    queryByIdServe,
    deleteArrServe,
    leadingOutFormwork,
    mbzjadd,
    mbzjedit,
    mbzjdelete,
    mbzjmbZjUpOrder,
    mbzjmbZjDownOrder,
} from './service/index'
import YchConstant from '@/api/YchConstant'
import commpVxeTable from '@/components/commp-vxe-table/commp-vxe-table.vue'
import assessCheckApi from './service/api'
import commpKindeditor from '@/components/commp-kindeditor/commpKindeditor.vue'
export default {
    components:{
        compSelector,
        serverEditing,
        commpVxeTable,
        commpKindeditor,
    },
    data(){
        return{
            fileTemplateIncreaseKindeditorId:'fileTemplateIncreaseKindeditorId'+Date.now(),
            windowInnerHeight:window.innerHeight,
            fchapterKindeditorId:'fchapterKindeditorId'+Date.now(),
            chapterKindeditorKey:null,
            spinning:true,
            form: this.$form.createForm(this, { name: 'coordinated' }),
            visibleShow:false,
            confirmLoading:false,
            typeSelect:typeSelect,
            formState:{},
            rules:{
                fmbbt: [
                    { required: true, message: '请输入模板标题', trigger: 'blur' },
                ],
                fmblx1: [
                    { required: true, message: '请输入模板类型1', trigger: 'blur' },
                ],
            },
            // rules:{
            //     fgcyxm: [{
            //         required: true,
            //         message: '请输入观察员姓名',
            //         trigger: 'blur',
            //     }],
            // },
            formRequer:'',
            optionsArr:[],
            submittedSuccessfully:false,
            renovate:false,
            fileList:[],
            fileListNameKey:null,
            drugProductionTemplateKey:null,
            tableKey:null,
            dataTableConfig:{
                api: assessCheckApi.mbzjqueryMbZjList,
                rowId: 'id',
                height:window.innerHeight - 530,
                fywflcode:blobType.fywflcodeArr[blobType.menuType.indexOf(this.$route.name.substring(this.$route.name.indexOf('__'),this.$route.name.indexOf('_a')+2))],
                pageSize:50,
                paramet:{
                }
            },
            formItem:[{
                label: '审评项目名称',
                model: 'fzjmc',
            }],
            columnsVxe:[{
                title: '序号',
                field: 'forder',
                width:100,
            },{
                title: '审评项目名称',
                field: 'fzjmc',
            },{
                title: '操作',
                field: 'id',
                slots: {
                    // 使用插槽模板渲染
                    default: 'operation_btn',
                },
                fixed: 'right',
                width:255
            }],
            chapterModel:{},
            rules1:{
                fzjmc: [
                    { required: true, message: '请输入审评项目名称', trigger: 'blur' },
                ],
                fmsmbnr: [
                    { required: true, message: '请输入模板描述', trigger: 'blur' },
                ],
            },
            chapterKey:null,
            chaptervisible:false,
            chapterTitle:'',
            activeKey:'审评情况描述'
        }
    },
    computed: {
        editMode(){
            return this.$store.state.permission.editMode
        },
    },
    watch:{
    },
    mounted(){
        
    },
    updated(){
        this.cancelLoading()
    },
    methods:{
        getData(newval){
            this.drugProductionTemplateKey = Date.now()
            this.spinning = true
            this.formState = newval
        //    if(!newval.id){
        //     this.fileList = []
        //     addServe().then(res=>{
        //         if(res.code == 200){
        //             this.formState.id = res.result.id
        //         }
        //     })
        //    }else{
            if(newval.id){
                this.dataTableConfig.paramet={fwjmbid:newval.id}
                this.tableKey = Date.now()
                this.renovate = true
                if(newval.fcflj){
                    //console.log('获取到了什么',newval)
                    this.fileList =[{
                        uid:-1,
                        name: newval.fmbbt+'.'+newval.fwjlx,
                        status: 'done',
                        url: bootConfig[process.env.NODE_ENV].locality_ApI+YchConstant.SPZX_SPCY + '/spcyRsWjmb/downWjmlById?id='+newval.id
                    }]
                }
            }
            this.spinning = false
            this.fileTemplateIncreaseKindeditorKey = Date.now()
            
        //    }
        },
        upAndDownClick(row,val){
            if(val){
                mbzjmbZjUpOrder({id:row.id}).then(res=>{
                    if(res.code == 200){
                        this.$refs.acceptanceRegistrationRef.searchEvent()
                    }else{
                        this.$message.message(res.message)
                    }
                })
            }else{
                mbzjmbZjDownOrder({id:row.id}).then(res=>{
                    if(res.code == 200){
                        this.$refs.acceptanceRegistrationRef.searchEvent()
                    }else{
                        this.$message.message(res.message)
                    }
                })
            }
        },
        addition(){//添加审评项目
            
            this.chapterTitle = '添加审评项目'
            this.chapterModel = {
                fwjmbid:this.formState.id
            }
            this.chaptervisible = true
            this.chapterKindeditorKey = Date.now()
            this.chapterKey = Date.now()
        },
        handleClick(row){
            this.chapterTitle = '编辑审评项目'
            this.chapterModel = {...row,fwjmbid:this.formState.id}
            this.chaptervisible = true
            this.chapterKey = Date.now()
        },
        deletionClick(row){
            var that = this
            this.$confirm({
                title:'您确认要删除吗？',
                // icon: createVNode(ExclamationCircleOutlined),
                onOk() {
                    mbzjdelete({id:row.id}).then(res=>{
                        if(res.code == 200){
                            that.$message.success('删除成功')
                        }else{
                            that.$message.warning(res.message)
                        }              
                        that.tableKey = Date.now()
                    })
                },
                
            });
        },
        chapterOk(){
            this.$refs.ruleForm1.validate(valid => {
                if (valid) {
                    if(this.chapterModel.id){
                        mbzjedit(this.chapterModel).then(res=>{
                            if(res.code == 200){
                                this.chaptervisible = false
                                this.tableKey = Date.now()
                                this.$message.success(res.message)
                            }else{
                                this.$message.warning(res.message)
                            }
                        })
                    }else{
                        mbzjadd(this.chapterModel).then(res=>{
                            if(res.code == 200){
                                this.chaptervisible = false
                                this.tableKey = Date.now()
                                this.$message.success(res.message)
                            }else{
                                this.$message.warning(res.message)
                            }
                        })
                    }
                } else {
                    return false;
                }
            });
        },
        //服务端编辑
        serverEdit(val){
            this.$refs.serverEditingRef.getData({...val,isTemplate:true})
        },
        manualSuccess(){
            queryByIdServe({id:this.formState.id}).then(result=>{
                if(result.code == 200){
                    let data = [{
                        uid:this.fileList[0].uid,
                        name: this.fileList[0].name,
                        status: 'done',
                        url:bootConfig[process.env.NODE_ENV].locality_ApI+YchConstant.SPZX_SPCY + '/spcyRsWjmb/downWjmlById?id='+this.formState.id
                    }]
                    this.fileList = data
                }
            })
        },
        cancelLoading(){
            let timer = setInterval((val)=>{
                this.spinning = false
                clearInterval(timer);
            },500)
            
        },
        DownloadTemplateClick(val){//下载模板
            var that = this
            this.DownloadTemplateLoading = true
            var fileName = val.fmbbt
            let param = { id:val.id}
            //console.log(val)
            //console.log(!val.fwjlx)
            
            if(!val.fwjlx){
                this.DownloadTemplateLoading = false
                this.$message.warning('暂无模板文件')
                return
            }
            var fileType = ['.doc','.docx','.xls','.xlsx']
            leadingOutFormwork(param).then((data) => {
                this.DownloadTemplateLoading = false
                if (!data) {
                    that.$message.warning('文件下载失败')
                    return
                }
                let currentType = ''
                if(fileType.indexOf(val.fwjlx) == 0){
                    currentType = 'application/msword'
                }else if(fileType.indexOf(val.fwjlx) == 1){
                    currentType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
                }else if(fileType.indexOf(val.fwjlx) == 2){
                    currentType = 'application/vnd.ms-excel'
                }else if(fileType.indexOf(val.fwjlx) == 3){
                    currentType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
                }
                    let url = window.URL.createObjectURL(new Blob([data], { type: currentType }))
                    let link = document.createElement('a')
                    link.style.display = 'none'
                    link.href = url
                    link.setAttribute('download', fileName + val.fwjlx)
                    //console.log('url----------',url)
                    document.body.appendChild(link)
                    link.click()
                    document.body.removeChild(link) //下载完成移除元素
                    window.URL.revokeObjectURL(url) //释放掉blob对象
            })
        },
        //在线编辑
        onlineEditingClick(val){
            // currentParametersFun(11111)
            this.$webOffice(`api/spzx-spcy/spcyRsWjmb/openWjbm?id=${val.id}`,
              `api/spzx-spcy/spcyRsWjmb/onLineSaveWjmb?id=${val.id}`+`-name=${val.fmbbt+val.fwjlx}`,
            //   `api/spzx-spcy/spcyRsWjmb/saveFileToPdf?id=${val.id}`,
            //   `api/spzx-spcy/spcyRsWjmb/saveFileGzToPdf?id=${val.id}`,
              )
        },
        handleRemove(){
            var that = this
            this.$confirm({
                title:'您确认要删除吗？',
                // icon: createVNode(ExclamationCircleOutlined),
                onOk() {
                    deleteArrServe({ids:that.formState.id}).then(res=>{
                        if(res.code == 200){
                            that.$message.success('删除成功')
                            that.fileList = []
                            that.fileListNameKey = Date.now()
                        }else{
                            that.$message.warning(res.message)
                        }
                    })
                },
                
            });
        },
        beforeUpload(file){
            this.fileList = [file];
            return false
        },
        leadingInClick({file}){//导入
            var that = this
            //console.log(file)
            if(file.status === 'removed'){
                deleteTemplateServe({id:this.formState.id}).then(res=>{
                    if(res.code == 200){
                        this.fileList = []
                    }else{
                        this.$message.warning(res.message)
                    }
                })
            }else{
                if(typeof file.uid !== 'undefined') {
                    // if(file.name.indexOf(".xls") !== -1 || file.name.indexOf(".xlsx") !==-1) {
                    const fileData = new FormData();
                    fileData.append("file",file);
                    fileData.append("fywflcode",blobType.fywflcodeArr[blobType.menuType.indexOf(this.$route.name.substring(this.$route.name.indexOf('__'),this.$route.name.indexOf('_a')+2))]);
                    fileData.append("id",this.formState.id);
                    addTemplateServe(fileData).then(res => {
                        //console.log('上传-------',res)
                        queryByIdServe({id:this.formState.id}).then(result=>{
                            if(result.code == 200){
                                this.fileList = [{
                                    uid:file.uid,
                                    name: file.name,
                                    status: 'done',
                                    url:bootConfig[process.env.NODE_ENV].locality_ApI+YchConstant.SPZX_SPCY + '/spcyRsWjmb/downWjmlById?id='+this.formState.id
                                }]
                            }
                        })
                        
                        
                    })
                }
                
            }
        },
        handleSubmit(val) {
            // e.preventDefault();
            var formState = {}
            this.form.validateFields((err, values) => {
                if (!err) {
                    if(!this.formState.fmsmbnr){
                        this.$message.warning('请先填写审评情况描述')
                        return
                    }
                    this.confirmLoading = true
                    formState = {
                        ...this.formState,
                        ...values
                    }
                    addServe(formState).then(res=>{
                        if(res.code == 200){
                            //console.log(res)
                            let data = res.result?res.result:{}
                            this.formState = {
                                fbz:data.fbz,
                                fcflj:data.fcflj,
                                fmbbt:data.fmbbt,
                                fmblx1:data.fmblx1,
                                fmblx2:data.fmblx2,
                                fmblx3:data.fmblx3,
                                fmblx4:data.fmblx4,
                                fmbzt:data.fmbzt,
                                fsqsxid:data.fsqsxid,
                                fwjccmc:data.fwjccmc,
                                fwjlx:data.fwjlx,
                                fywflcode:data.fywflcode,
                                id:data.id,
                                sysOrgCode:data.sysOrgCode,
                                fmsmbnr:data.fmsmbnr,
                                fmsmbbt:data.fmsmbbt,
                                fjcxmbt:data.fjcxmbt,
                            }
                            this.$message.success('保存成功')
                            this.submittedSuccessfully = true
                            this.visibleShow = val
                            this.tableKey = Date.now()
                            this.$emit('handleOk',true,this.renovate)
                        }
                        this.confirmLoading = false
                    })
                }
            });
            
        },
        tabPaneChange(val){
            //console.log(val)
        },
        handleOk(val){
            this.$refs.ruleForm.validate(valid => {
                if (valid) {
                    this.handleSubmit(val)
                } else {
                    return false;
                }
            });
        }
    }

}

</script>
<style lang="less">
/* .ant-form-item-label{
    font-weight: 600;
} */
.drug-production-template-model{
    .ant-modal-title{
        font-weight: 600;
    }
    .ant-modal-header{
        background: #5ca3e5;
    }
    .ant-modal-body{
        padding: 8px;
    }
    .file-temp-modal .ant-upload-list{
        display: block !important;
    }
    .file-temp-modal .ant-upload-list-item{
        display: inline-block !important;
    }
    .ant-modal-footer .ant-btn-primary{
        border: 1px solid #5ca3e5 !important;
        background-color: #5ca3e5 !important;
        color: #fff !important;
    }
    .ant-modal-footer{
        padding: 0;
    }
    .drug-production-template-form{
        display: flex;
        flex-wrap: wrap;
        .ant-form-item{
            width: calc(50% - 16px);
            display: flex;
        }
        .ant-form-item-control-wrapper{
            flex: 1;
        }
        .ant-form-item-label label{
            width: 90px !important;
            display: inline-block;
        }
    }
    .fileTemplate-increase-tabs{
        border: 1px solid #38f;
        border-top: none;
        padding: 3px;
        .item-box-v{
            display: flex;
            align-items: center;
            margin: 10px 0;
            .text-v{
                font-size: 16px;
                font-weight: 600;
                color: #242424;
            }
        }
    }
}
.fileTemplate-chapter-modal{
    .fileTemplate-chapter-box{
        .ant-form-item{
            display: flex;
        }
        .ant-form-item-label{
            width: 107px;
        }
        .ant-form-item-control-wrapper{
            flex: 1;
        }
    }
    .ant-modal-body{
        padding: 8px;
    }
}

    
</style>